package org.redmagic.service.controller;

import javax.servlet.http.HttpServletRequest;

import org.redmagic.domain.Property;

public abstract class AbstractLinkedDataController {

	protected String getLinkedDataProperty(HttpServletRequest request, String path, Property property) {
		String baseUrl = getBaseUrl(request);
		String normalizedPath = normalize(path);
		String propertyString = getPropertyAsString(property);
		return baseUrl + normalizedPath + propertyString;
	}

	private String getPropertyAsString(Property property) {
		String base = property.getName();
		if (property.getTags().isEmpty()) {
			return base;
		} else {
//			String orderedTags = Tags.toOrderedString(property.getTags()); // FIXME TODO
//			return base + "?" + orderedTags;
			throw new RuntimeException("I'm broken!");
		}
	}

	protected String getBaseUrl(HttpServletRequest request) {
		String requestUrl = request.getRequestURL().toString();
		String contextPath = request.getContextPath();
		int index = requestUrl.indexOf(contextPath);
		return requestUrl.substring(0, index + contextPath.length() + 1);
	}
	
	
	protected String normalize(String path) {
		if (path.startsWith("/")) {
			path = path.replaceFirst("/", "");
		}
		
		if (!path.endsWith("/")) {
			path = path + "/";
		}
		
		return path;
	}
}
